const { UserInputError } = require("apollo-server-express");

const articleResolvers = {
  Query: {
    async articles(parent, { offset, limit }, context, info) {
      // const [articles, articlesCount] = await Promise.all([
      //   dataSources.articles.getArticles({ offset, limit }),
      //   dataSources.articles.getArticleCount(),
      // ]);

      // return {
      //   articles,
      //   articlesCount,
      // };
      context.offset = offset;
      context.limit = limit;
      return {};
    },
  },

  Mutation: {
    async createArticle(parent, { article }, { dataSources, user }, info) {
      article.author = user._id;
      const ret = await dataSources.articles.createArticle(article);
      // 根据用户id获取用户消息填充到 article.author 中
      return {
        article: ret,
      };
    },
  },
  Article: {
    author: async (parent, args, { dataSources }, info) => {
      const user = await dataSources.users.findById(parent.author);
      return user;
    },
  },

  AticlesPayload: {
    async articles(parent, args, { dataSources, offset, limit }, info) {
      const articles = await dataSources.articles.getArticles({
        offset,
        limit,
      });
      return articles;
    },
    articlesCount: async (parent, args, { dataSources }, info) => {
      const count = await dataSources.articles.getArticleCount();
      return count;
    },
  },
};

module.exports = articleResolvers;
